/*
 * @customMade: 赵宇
 * @Date: 2022-01-10 10:34:55
 * @LastEditTime: 2023-02-22 17:25:46
 * @LastEditors: zhao 13370229059@163.com
 * @FilePath: \pcj\src\api\index.js
 */
import axios from 'axios';
import { ElNotification, ElLoading } from 'element-plus';
let instance = axios.create({
  baseURL: import.meta.env.DEV ? 'api/' : 'api/services/app',
  timeout: 15000,
  responseType: 'json',
  validateStatus(status) {
    return status === 200;
  }
});
let loadingInstance, timeout;
// 拦截请求
instance.interceptors.request.use(
  config => {
    loadingInstance = ElLoading.service({
      text: '加载中',
      background: 'transparent'
    });
    timeout = setTimeout(() => {
      if (loadingInstance) loadingInstance.close();
    }, 4000);
    let token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = 'Bearer ' + token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    let { data, status } = response;
    loadingInstance.close();
    clearTimeout(timeout);
    // 状态为 200 但是是错误的
    if (status === 200 && !data.success) {
      ElNotification({
        title: '提示',
        message: data.error.message || '错误，请联系管理员！',
        type: 'error'
      });
      return Promise.reject();
    }
    return data;
  },
  ({ response }) => {
    let { data } = { ...response };
    let { error } = { ...data };
    loadingInstance.close();
    clearTimeout(timeout);
    let message = error.message || '请联系管理员！';
    ElNotification({
      title: '错误',
      message,
      type: 'error'
    });
    return Promise.reject(error);
  }
);
const post = (url, params = {}, config = { headers: { 'Content-Type': 'application/json' } }) => {
  return instance.post(`${url}`, params, config);
};
const get = (url, params = {}) => {
  let _params;
  let _paramsarr = [];
  let obj = {};
  Object.keys(params).map(r => {
    if (params[r] !== null) {
      obj[r] = params[r];
    }
  });
  params = obj;
  if (Object.is(params, undefined)) {
    _params = '';
  } else {
    for (let key in params) {
      if (params.hasOwnProperty(key) && params[key] !== null) {
        _paramsarr.push(`${key}=${params[key]}`);
      }
    }
    _paramsarr.length === 0 ? (_params = '') : (_params = '?' + _paramsarr.join('&'));
  }
  return instance.get(`${url}${_params}`);
};
const request = {
  post,
  get
};
export default request;
export { post, get };
